﻿#include "socket.h"
#include "channel.h"
#include "eventloop.h"
#include "connection.h"
#include "acceptor.h"
#include <iostream>
#include <unordered_map>

std::unordered_map<int, ConnectionPtr> g_conn_map;
uint64_t conn_id = 0;


void ConnectionEstablish(const ConnectionPtr &conn)
{

    std::cout << "server establish connection" << std::endl;
}

void MessageHandler(const ConnectionPtr &conn, Buffer *buf)
{
    std::cout << "server recv: " << buf->getReadAddr() << std::endl;
    buf->moveReadStep(buf->getReadSize());
    std::string response = "sfwnb";
    conn->send(response.c_str(), response.size());
    // TEST: 测试连接关闭是否有效
    conn->shutDown();
}


void ConnectionDestroy(const ConnectionPtr &conn)
{
    int client_fd = conn->getSockfd();
    auto it = g_conn_map.find(client_fd);
    if(it != g_conn_map.end())
    {
        g_conn_map.erase(it);
    }
}


bool AcceptNewClient(EventLoop *eloop, int connfd)
{
    // 创建连接
    ConnectionPtr conn = std::make_shared<Connection>(eloop, conn_id, connfd);
    // 设置回调
    conn->setMessageCallback(std::bind(MessageHandler, std::placeholders::_1, std::placeholders::_2));
    conn->setCloseCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->setConnectCallback(std::bind(ConnectionEstablish, std::placeholders::_1));
    conn->enableInactiveRelease(10);
    conn->establishConnection();
    g_conn_map.insert(std::make_pair(connfd, conn));
    conn_id++;
    return true;
}

int main() 
{
    // 创建epoller
    EventLoop eloop;
    Acceptor acceptor(&eloop, 58888, "127.0.0.1");
    // 设置新连接回调
    acceptor.setNewConnectionCallback(std::bind(AcceptNewClient, &eloop, std::placeholders::_1));
    // 监听
    acceptor.listen();
    eloop.start();

    return 0;
} 